package com.yyn.Learning.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyn.Learning.entity.EduSubject;
import com.yyn.Learning.entity.excel.SubjectData;
import com.yyn.Learning.service.EduSubjectService;
import com.yyn.servicebase.exceptionhandler.CustomException;
//import com.yyn.servicebase.exceptionhandler.GlobalExceptionHander;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService subjectService;
    public SubjectExcelListener(EduSubjectService subjectService) {
       this.subjectService= subjectService;
    }

    @Override
//    一行一行的读取excel内容(subjectData文件内容)/
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
//        1\判断是否为空
        if(subjectData == null){
            throw new CustomException(20001,"该文件无数据");
        }
//        每次读取有两个值  一级 二级(但不能重复)
//        读取后就放在数据库中\
//        一一级
        EduSubject eduOneSubject= this.checkOneSubject(subjectService, subjectData.getOneSubjectName());
        if(eduOneSubject == null){//搜不到 没有重复
//            把值存到数据表中
            eduOneSubject = new EduSubject();
            eduOneSubject.setParentId("0");
            eduOneSubject.setTitle( subjectData.getOneSubjectName());
            subjectService.save(eduOneSubject);
        }
        //        二级
        String pid = eduOneSubject.getId();//如果没有一级id 二级不知道对应的是哪个
        EduSubject eduTwoSubject= this.checkTwoSubject(subjectService, subjectData.getTwoSubjectName(),pid);
        if(eduTwoSubject == null){//搜不到 没有重复
//            把值存到数据表中
            eduTwoSubject = new EduSubject();
            eduTwoSubject.setParentId(pid);
            eduTwoSubject.setTitle( subjectData.getOneSubjectName());
            subjectService.save(eduTwoSubject);
        }
    }

//    判断一级
//    parent_id = 0 代表一级   非0 为二级分类
//    title 为数据库的一级名称
    public EduSubject checkOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> EduSubjectWrapper = new QueryWrapper<>();
        EduSubjectWrapper.eq("parent_id","0");
        EduSubjectWrapper.eq("title",name);
        EduSubject one = subjectService.getOne(EduSubjectWrapper);
        return one;
    }
    //    判断二级
//    parent_id = 0 代表一级   非0 为二级分类
//    title 为数据库的一级名称
    public EduSubject checkTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> EduSubjectWrapper = new QueryWrapper<>();
        EduSubjectWrapper.eq("parent_id",pid);
        EduSubjectWrapper.eq("title",name);
        EduSubject two = subjectService.getOne(EduSubjectWrapper);
        return two;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
